package com.pactera.asmp.server.service;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.pactera.asmp.server.common.constants.ResultCode;
import com.pactera.asmp.server.common.logprint.utils.StringUtils;
import com.pactera.asmp.server.common.utils.FileUtils;
import com.pactera.asmp.server.dao.IssueMapper;
import com.pactera.asmp.server.entity.IssueSearchDTO;
import com.pactera.asmp.server.entity.ResponseResult;
import com.pactera.asmp.server.pojo.Issue;
import com.pactera.asmp.server.pojo.PieChart;
import com.pactera.asmp.server.pojo.ProcessInfo;
import com.pactera.asmp.server.pojo.ProjectInfo;
import com.pactera.asmp.server.utils.AssertUtil;
import com.pactera.asmp.server.utils.DateUtil;
import com.pactera.asmp.server.utils.PageDataResult;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.support.ServletUriComponentsBuilder;

import java.util.Date;
import java.util.List;

/**
 * @ProjectName: asmpserver
 * @Package: com.pactera.asmp.server.service
 * @ClassName: IssueServiceImpl
 * @Author: lvzhiqiang
 * @Description: IssueService 业务实现
 * @Date: 2019/8/2 13:56
 * @Version: 1.0
 */
@Service
public class IssueServiceImpl implements IssueService {
    private static final Logger logger = LoggerFactory
            .getLogger(IssueServiceImpl.class);

    @Autowired
    public IssueMapper mIssueMapper;

    @Autowired
    public ScreenDataService screenDataService;

    @Autowired
    public ProjectManagerService projectManagerService;

    @Value("${trace.upload.file.base.path}")
    private String mTraceFileUploadPath;


    @Override
    public PageDataResult getIssues(IssueSearchDTO issueSearchDTO, int page, int limit) {
        if (null != issueSearchDTO) {
            if (StringUtils.isNotEmpty(issueSearchDTO.getIssueCreateTime())
                    && StringUtils.isEmpty(issueSearchDTO.getIssueCreateTimeEnd())) {
                issueSearchDTO.setIssueCreateTimeEnd(DateUtil.format(new Date()));
            } else if (StringUtils.isEmpty(issueSearchDTO.getIssueCreateTime())
                    && StringUtils.isNotEmpty(issueSearchDTO.getIssueCreateTimeEnd())) {
                issueSearchDTO.setIssueCreateTime(DateUtil.format(new Date()));
            }
            if (StringUtils.isNotEmpty(issueSearchDTO.getIssueCreateTime())
                    && StringUtils.isNotEmpty(issueSearchDTO.getIssueCreateTimeEnd())
                    && issueSearchDTO.getIssueCreateTimeEnd().compareTo(issueSearchDTO.getIssueCreateTime()) < 0) {
                    String temp = issueSearchDTO.getIssueCreateTime();
                    issueSearchDTO.setIssueCreateTime(issueSearchDTO.getIssueCreateTime());
                    issueSearchDTO.setIssueCreateTimeEnd(temp);
            }
        }

        PageDataResult pageDataResult = new PageDataResult();
        PageHelper.startPage(page, limit);
        if(StringUtils.isNotEmpty(issueSearchDTO.getProjectName())) {
            issueSearchDTO.setProjectName("%" + issueSearchDTO.getProjectName() + "%");
        }
        if(StringUtils.isNotEmpty(issueSearchDTO.getIssueType())) {
            issueSearchDTO.setIssueType("%" + issueSearchDTO.getIssueType() + "%");
        }
        List<IssueSearchDTO> list = mIssueMapper.getIssue(issueSearchDTO);
        PageInfo<IssueSearchDTO> pageInfo = new PageInfo<>(list);
        pageDataResult.setTotals((int) pageInfo.getTotal());
        pageDataResult.setList(list);
        return pageDataResult;
    }

    @Override
    public String delIssues(List<Integer> datas) {
        if (mIssueMapper.deleteByPrimaryKeys(datas) > 0) {
            return ResultCode.SUCCESS.message();
        }
        return ResultCode.FAIL.message();
    }

    @Override
    public String delIssue(Integer id) {
        if (mIssueMapper.deleteByPrimaryKey(id) > 0) {
            return ResultCode.SUCCESS.message();
        }
        return  ResultCode.FAIL.message();
    }

    @Override
    @Transactional(propagation = Propagation.REQUIRED,isolation = Isolation.DEFAULT,rollbackFor={RuntimeException.class, Exception.class})
    public boolean addIssue(Issue issue, MultipartFile file) {
        String basePath = ServletUriComponentsBuilder.fromCurrentContextPath().toUriString();
        logger.error(basePath);
        StringBuilder basePathStr = new StringBuilder(mTraceFileUploadPath);
        basePathStr = basePathStr.append("/").append(issue.getProjectName()).append("/").append(issue.getIssueProcessName()).append("/").append(issue.getIssueCreateTime().getTime()).append("/").append(file.getOriginalFilename());
        issue.setTracePath(basePathStr.toString());
        Date date = new Date(System.currentTimeMillis());
        issue.setIssueCreateTime(date);
        issue.setIssueUploadTime(date);
        boolean status = FileUtils.saveIssueTraceFile(issue.getTracePath(), file);
        if(mIssueMapper.insert(issue) > 0 && status){
            return true;
        }else {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
        }
        return false;
    }

    @Override
    public ResponseResult addIssue(Issue issue) {
        AssertUtil.notNull(issue,"参数异常");
        Date date = new Date(System.currentTimeMillis());
        issue.setIssueCreateTime(date);
        issue.setIssueUploadTime(date);
        mIssueMapper.insert(issue);

        ProjectInfo projectInfo = projectManagerService.selectByName(issue.getProjectName());
        if(projectInfo != null && projectInfo.getId() != null) {
            screenDataService.issueChanged(projectInfo.getId());
        }
        return ResponseResult.defaultSuccess(issue);
    }


    /**
     * @Method getChartData
     * @Description 查询图表数据
     * @param:
     * @return: PieChart
     * @auther:
     * @date:
     */
    @Override
    public PieChart getChartData(String name) {
        return mIssueMapper.getChartData(name);
    }

    @Override
    public  PieChart getProblemCount(String projectName, String versionData) {
        return mIssueMapper.getProblemCount(projectName, versionData);
    }

    @Override
    public List<ProcessInfo> getTopProblemList(String projectName){
        return mIssueMapper.getTopProblemList(projectName);
    }
}
